package com.snail.oauth;

import com.common.util.StringUtil;
import com.tangjiu.auth.entity.AuthAuthority;
import com.tangjiu.auth.entity.AuthMenu;
import com.tangjiu.auth.service.AuthAuthorityService;
import com.tangjiu.auth.service.AuthMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author HOU
 * @descripton 自定义的Metadata，通过当前请求地址，获取该地址所需要的角色
 * @date 2021/5/31
 */
@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private AuthMenuService menuService;
    @Autowired
    private AuthAuthorityService authorityService;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher(File.separator);

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        List<ConfigAttribute> attributes = new ArrayList();
        //获取请求的url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<AuthMenu> menus = menuService.list();
        for (AuthMenu menu : menus) {
            if (!StringUtil.isEmpty(menu.getPath())) {
                if (antPathMatcher.match("/"+menu.getPath()+"**", requestUrl)) {
                    List<AuthAuthority> authAuthorities = authorityService.getByMenuId(menu.getId());
                    int size = authAuthorities.size();
                    String[] authStrs = new String[size];
                    for (int i = 0; i < size; i++) {
                        attributes.add(new SecurityConfig(authAuthorities.get(i).getValue()));
                    }
                    return attributes;
                }
            }
        }
        // 如果没有匹配，则默认全部可以访问
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
